﻿using System.Collections.Generic;
using System.Linq;
using ClientOverflow.DataTransferObjects;

namespace ClientOverflow.CommunicationServices.Data
{
    /// <summary>
    /// QuestionsFactory is resposible for generating questions as objects from DB. In addition, it's
    /// resposible for generating question as object based on crieteria.
    /// </summary>
    public static class QuestionsFactory
    {
        public static DataObjects.Question CreateQuestion(Question dtoQuestion, User user)
        {
            var questionOwner = DataObjects.User.Queryable.First(dbUser => dbUser.Email == user.Email);

            var question = dtoQuestion.ToDataObject();
            question.Owner = questionOwner;

            return question;
        }

        public static IEnumerable<Question> GetAllQuestions()
        {
            return DataObjects.Question.Queryable
                .ToList()
                .Select(dbQuestion => dbQuestion.ToDto());
        }

        public static DataObjects.Question FindQuestion(Question question)
        {
            return DataObjects.Question.Queryable.First(dbQuestion => question.ID == dbQuestion.ID);
        }

        public static Question FindQuestionByAnswer(Answer answer)
        {
            return DataObjects.Question.Queryable
                .First(dbQuestion => dbQuestion.Answers.Any(dbAnswer => dbAnswer.ID == answer.ID))
                .ToDto();
        }
    }
}